import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-name-editor',
  templateUrl: './name-editor.component.html',
  styleUrls: ['./name-editor.component.scss']
})
export class NameEditorComponent implements OnInit {

  /**
   * 表单控件实例，通过表单控件实例可以对表单状态进行监听、修改和校验
   */
  public nameEditor: FormControl = new FormControl('Angular');

  public fomGroup: FormGroup = new FormGroup({
    address: new FormControl('武汉市江夏区佛祖岭街道万科魅力之城北区3栋A1单元1002'),
    age: new FormControl(23)
  });

  public formArray: FormGroup = new FormGroup({
    name: new FormControl('hbche'),
    age: new FormControl(23),
    address: new FormGroup({
      city: new FormControl('wuhan'),
      street: new FormControl('fozuling')
    })
  });

  public profileForm: FormGroup;

  constructor(private formBuilderService: FormBuilder) { }

  ngOnInit() {
    this.profileForm = this.formBuilderService.group({
      name: ['NgZorro', Validators.required],
      link: ['https://ng.ant.design/', Validators.pattern(/^https:\/\/[a-z.\/]+$/)],
      address: this.formBuilderService.group({
        province: ['浙江'],
        city: ['杭州']
      })
    });
  }

  /**
   * 显示表单控件的值
   * 1. 通过可观察对象 valueChanges，你可以在模板中使用 AsyncPipe 或在组件类中使用 subscribe() 方法来监听表单值的变化。
   * 2. 使用 value 属性。它能让你获得当前值的一份快照。
   */
  public showFormValue(): void {
    this.nameEditor.registerOnChange(value => {
      console.log(value);
    });
  }

  /**
   * 重值表单的值
   */
  public resetName(): void {
    this.nameEditor.setValue('Qt');
  }

  /**
   * 表单提交事件
   * @param event
   */
  public onSubmit(event: Event): void {
    console.log(event);
    console.log(this.fomGroup);
  }

  /**
   * 只更新表单组中指定的表单
   */
  public updateFormGroup(): void {
    this.formArray.patchValue({
      name: 'Angular',
      address: {
        street: '佛祖岭街道'
      }
    });
  }

  /**
   * 
   */
  public submitArray(): void {
    console.log(this.formArray);
  }

  // 使用表单验证
  // 1. 导入验证函数
  // 2. 把验证器添加到表单响应的字段
  // 3. 添加逻辑来处理表单验证状态

}
